﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections.Specialized;
using System.Configuration;
using System.Net.Mail;
using System.Net;
using ExtraClub.Domain.Entities;
using System.Diagnostics;
using System.Text;

namespace ExtraClub.Domain {
    public static class poll {
        public const string DummyPageUrl = "service.ashx";
        private const double POLLING_PERIOD = 10; // secconds 
        private const string DummyCacheItemKey = "SmartMassEmailDummyCacheItem";

        public static void RegisterCacheEntry() {
            if (null != HttpContext.Current.Cache[DummyCacheItemKey]) return;

            HttpContext.Current.Cache.Add(DummyCacheItemKey, "Test", null, DateTime.MaxValue,
                TimeSpan.FromSeconds(POLLING_PERIOD), System.Web.Caching.CacheItemPriority.NotRemovable,
                new System.Web.Caching.CacheItemRemovedCallback(CacheItemRemovedCallback));
        }

        public static void CacheItemRemovedCallback(string key, object value, System.Web.Caching.CacheItemRemovedReason reason) {
            System.Diagnostics.Debug.WriteLine("Cache item callback: " + DateTime.Now.ToString());
            System.Diagnostics.Debug.WriteLine("Begin DoWork...");
            System.Diagnostics.Debug.WriteLine("Running as: " + System.Security.Principal.WindowsIdentity.GetCurrent().Name);

            Job.SendBatchMail();

            System.Diagnostics.Debug.WriteLine("End DoWork...");

            HitPage();
        }
        private static void HitPage() {
            string siteprefix = ConfigurationManager.AppSettings.Get("SitePrefix");
            System.Net.WebClient client = new System.Net.WebClient();

            NameValueCollection q = new NameValueCollection();
            q["p"] = HttpUtility.UrlEncode(DateTime.Now.ToString("yyyy.MM.dd:HH:mm"));
            client.QueryString = q;
            client.DownloadData(siteprefix + DummyPageUrl);
        }
    }
}